<?php
class AclPermissionModel extends ModelArray
{
    protected $resourceId = 'AdminResource';
    protected static $instance;

    public static function GetInstance()
    {
        return self::$instance ? self::$instance : self::$instance = new AclPermissionModel();
    }

    public function LoadFields()
    {
        $this->AddField('group_id', 'varchar', false, true);
        $this->AddField('resource_id', 'varchar', false, true);
        $this->AddField('actions');

        $this->SetForeignKey('group_id', AclGroupModel::GetInstance()->GetTableName(), 'id');
        $this->SetForeignKey('resource_id', AclResourceModel::GetInstance()->GetTableName(), 'id');
    }

    protected function GetPrimaryKeyValue(&$item)
    {
        $pk = $this->GetPrimaryKey();
        return $item[$pk] = isset($item[$pk]) ? $item[$pk] : $item['group_id'].'::'.$item['resource_id'];
    }

    public function FindById($id, $fields = null)
    {
        $cond = new SqlCondition();
        $cond->AddString('group_id::resource_id', $id);
        return $this->FindOne($cond);
    }

    public function HasPermission($group_id, $resource_id, $action_id)
    {
        $item = $this->FindById("$group_id::$resource_id");
        $actions = String::ToArray($item['actions']);
        return in_array($action_id, $actions);
    }

    public static function Authorize($user_id, $resource_id, $action_id)
    {
        if (!$resource_id) return;
        if (!$user_id)
            throw new NoPermissionException();
        $group_id = CmsUserModel::GetInstance()->GetGroupIdById($user_id);
        if (!self::GetInstance()->HasPermission($group_id, $resource_id, $action_id))
            throw new NoPermissionException();
    }
}
?>